#include <QPainter>
#include <QDebug>
#include "ca-pathfinding/grids/tile.h"
#include"ca-pathfinding/grids/grid.h"
#include "objective.h"
#include "objectfactory.h"
#include "arena.h"



Objective::Objective():Object()
{
    type=ot::OBJECTIVE;
    health=1000;
    firing_range=450;
    angle=0.0f;
    rot=0.0f;
    rotacc=0.5f;
    rotfriction=0.93f;
    firing=false;
    aiming=false;
    iteration=0;
    health=100;
    alive=true;
    texture=QPixmap(":/resources/turret.png");
}

void Objective::paint(QPainter *painter, const QStyleOptionGraphicsItem *,QWidget *)
{
    painter->drawPixmap(boundingRect().toRect(),texture);
}

QRectF Objective::boundingRect() const
{
    const static QRectF r(-texture.width()/2,-texture.height()/2,texture.width(),texture.height());
    return r;

}

void Objective::purge()
{
    texture=QPixmap(":/resources/turret_broken.png");
    alive=false;
}

void Objective::control()
{

    int px=grid->player->tile->x;
    int py=grid->player->tile->y;
    int tx=tile->x;
    int ty=tile->y;
    float d=distance(px,py,tx,ty);
    if(distance(tx,ty,px,py)<=firing_range)
    {
        aiming=true;
        firing=false;
    }
    else aiming=firing=false;


    if(aiming)
    {
        if(px>tx && py<=ty)
            aiming_angle=round(180*asin(distance(tx,py,px,py)/d)/M_PI);
        else if(px>tx && py>ty)
            aiming_angle=90+round(180*asin(distance(px,ty,px,py)/d)/M_PI);
        else if(px<=tx && py>ty)
            aiming_angle=180+round(180*asin(distance(tx,py,px,py)/d)/M_PI);
        else aiming_angle=270+round(180*asin(distance(px,ty,px,py)/d)/M_PI);


        if(aiming_angle==360)aiming_angle=0;

        int th1=angle+360-aiming_angle;

        if(th1<0)th1+=360;
        else if(th1>359)th1-=360;

        int th2=360-th1;

        if(th2<0)th2+=360;
        else if(th2>359)th2-=360;

        if(fabs(aiming_angle-angle)<0.5f)
        {
            rot=0.0f;
            aiming=false;
            firing=true;
        }
        else if(th1<th2) rot+=rotacc;
        else rot-=rotacc;
    }
    if(firing)fire();
}

void Objective::physics()
{
    if(fabs(rot)<rotacc)rot=0;
    else rot*=rotfriction;
}

void Objective::step()
{

    bool rep=(rot==0 && angle!=int(angle));
    if(rep)
    {
        float x=angle-int(angle);
        if(x>0.5f)rot=x+1;
        else rot=x;
    }
    rotate(-rot);
    angle-=rot;
    if(rep)rot=0;
    if(angle<0) angle+=360;
    else if(angle>360) angle-=360;

}
void Objective::fire()
{
    static ObjectFactory f(purgatory);
    if(!iteration)
    {
        Bullet* b=f.createBullet(this);
        if(!b->scene())arena->addBullet(b);
        b->resetTransform();
        b->setPos(scenePos());
        b->rotate(angle);
    }

    iteration=(iteration+1)%50;
}

void Objective::hit(int val)
{
        health-=val;
        if(health<=0)purge();
}
